CSS Z-Index

Home / CSS / CSS Z-Index

CSS Z-Index


CSS Z-Index:

In CSS, the z-index property is used to control the stacking order of positioned elements (i.e., elements with a position property value other than static). It determines which elements appear in front of or behind other elements on the web page. The z-index property takes an integer value, and elements with a higher z-index value will be displayed in front of elements with a lower z-index value.

Here's how the z-index property works:

Positive Values: Elements with a higher positive z-index value will be displayed in front of elements with lower z-index values. For example:


<style>
    .element1 {
      z-index: 2;
    }

    .element2 {
      z-index: 1;
    }
  </style>

In this case, .element1 will be displayed in front of .element2.

Negative Values: Elements with a negative z-index value can also be used. Elements with lower negative values will be displayed in front of elements with higher negative values. For example:

<style>
    .element1 {
      z-index: -1;
    }

    .element2 {
      z-index: -2;
    }
  </style>

Here, .element1 will be displayed in front of .element2.

Auto: By default, all positioned elements have a z-index value of auto. Elements with auto are displayed in the order they appear in the HTML source code and can be layered based on their HTML structure.

Stacking Context: Elements with a higher z-index value will also be displayed in front of elements with lower values within the same stacking context. A stacking context is an element that has a position value of absolute, relative, fixed, or sticky, along with a few other properties.

For example, if you have a parent element with a higher z-index value than its child, the child's z-index will still be relative to its parent's z-index, not to other elements on the page.


<style>
    .parent {
      position: relative;
      z-index: 3;
    }

    .child {
      position: absolute;
      z-index: 2;
    }
  </style>

In this case, the .child element will be displayed in front of other elements within the same parent.